// 状态管理
import {computed, ref} from "vue";
import pdfIcon from "@/asserts/documentTypeSvg/pdf.svg";
import wordIcon from "@/asserts/documentTypeSvg/word.svg";
import excelIcon from "@/asserts/documentTypeSvg/excel2.svg";
import pptIcon from "@/asserts/documentTypeSvg/ppt.svg";
import imageIcon from "@/asserts/documentTypeSvg/image2.svg";
import audioIcon from "@/asserts/documentTypeSvg/video.svg";
import videoIcon from "@/asserts/documentTypeSvg/video.svg";
import archiveIcon from "@/asserts/documentTypeSvg/zip.svg";
import htmlIcon from "@/asserts/documentTypeSvg/html.svg";
import textIcon from "@/asserts/documentTypeSvg/txt2.svg";
import wenBenIcon from "@/asserts/documentTypeSvg/wenBen.svg";
import sqlIcon from "@/asserts/documentTypeSvg/sql.svg";
import chengXuIcon from "@/asserts/documentTypeSvg/ChengXu.svg";
import fileIcon from "@/asserts/documentTypeSvg/file.svg";
import {getFileType} from "@/views/documentManager/components/ts/fileTypeManager";
import {message} from "@/utils/ElmessasgeUtils";
import {getFileBrowserSortConfig, getUserInfo, setFileBrowserSortConfig} from "@/utils/system";
import router from "@/router";
import {draggedItem, dragOverItem, dragOverParentFolder} from "@/views/documentManager/components/ts/dragItem";
import {getAllFilesByBucketName, getBucketFileUrl, moveBucketFile} from "@/api/documentManage/minioManager2";
import {getBucketNameByUserId} from "@/api/documentManage/documentUserBucketName";
import type {FileItem, StarFileItem} from "@/type/documentManager/FileItem";

export const enum MenuItemType {
    PERSONAL_FILE_LIST = "personalFileList", // 我的空间
    PUBLIC_FILE_LIST = "PublicFileList",     // 公共空间
    STAR_FILE_LIST = "starFileList",         // 我的收藏
    RECYCLE_FILE_LIST = "recycleFileList",
    RECENT_OPEN_FILE_LIST = "recentOpenFileList",
}

/**
 * ============================  变量区域  ==============================
 */
const currentBucketName = ref('')


// 默认是个人空间列表
const currentMenu = ref(MenuItemType.PERSONAL_FILE_LIST.valueOf());

// 文件浏览器当前目录
const currentPath = ref<string>('');

// 记录路径历史
const pathHistory = ref<string[]>([]);

// 排序状态
export const sortField = ref<string>('name');
export const sortOrder = ref<string>('asc');

// 当前选中文件
export const selectedItem = ref<FileItem | null>(null);

// ---------------------- 私有变量 --------------------
const loading = ref(false);
const currentItems = ref<FileItem[]>([]);


// 搜索使用的Key
const searchKeyword = ref<string>("");


// 添加排序后的项目列表，用于显示
export const sortedItems = computed(() => {
    // 先进行搜索过滤
    let filteredItems = [...currentItems.value];

    if (searchKeyword.value.trim()) {
        const keyword = searchKeyword.value.trim().toLowerCase();
        filteredItems = filteredItems.filter(item =>
            item.name.toLowerCase().includes(keyword)
        );
    }

    // 然后进行排序
    return filteredItems.sort((a, b) => {
        let compareResult = 0;

        // 文件夹始终排在前面
        if (a.folderFlag && !b.folderFlag) return -1;
        if (!a.folderFlag && b.folderFlag) return 1;

        // 根据当前排序字段比较
        if (sortField.value === 'name') {
            compareResult = a.name.localeCompare(b.name);
        } else if (sortField.value === 'size') {
            compareResult = a.size - b.size;
        } else if (sortField.value === 'lastModified') {
            compareResult = a.lastModified.getTime() - b.lastModified.getTime();
        }

        // 应用排序顺序
        return sortOrder.value === 'asc' ? compareResult : -compareResult;
    });
});


// 是否可以导航到上一级目录
const canNavigateUp = computed(() => {

    return currentPath.value != '';

});

/**
 * ============================= 方法区域 =================================
 */

// 更新 bucketName, true personal, false 为 public
export async function updateBucketName(type: boolean) {
    currentPath.value = '';
    pathHistory.value = [];

    if (type) {
        await updatePersonalBucketName();
    } else {
        currentBucketName.value = 'public';
    }
}

export async function updatePersonalBucketName() {
    let userInfo = getUserInfo();
    if (userInfo) {
        let res: any = await getBucketNameByUserId();
        if (res.data.code == 200) {
            let _data: any = res.data.data;
            currentBucketName.value = _data.bucketName;
        } else {
            message("获取文件桶名失败", 'error')
            return
        }


    } else {
        message("登陆信息为空，请重新登陆", 'error')
        router.push('/login')
        return;
    }
}

// 从后端加载文件列表
const updateFileListFromBackEnd = async (path: string) => {
    try {
        loading.value = true;
        currentItems.value = [] // 要清空，否则刷新时页面显示有BUG

        let response: any;
        response = await getAllFilesByBucketName(currentBucketName.value, path);

        if (response.data.code === 200) {
            currentItems.value = response.data.data.map((item: any) => ({
                name: item.name,
                path: item.path,
                folderFlag: item.folderFlag,
                size: item.size || 0,
                lastModified: new Date(item.lastModified)
            }));

            getOriginSortConfig()
        } else {
            message("获取文件列表失败", 'error')
        }

    } catch (err) {
        message('加载文件列表失败', 'error');
    } finally {
        loading.value = false;
    }
};

// 从当前目录刷新文件列表
async function updateCurrentPathFileList() {
    await updateFileListFromBackEnd(currentPath.value);
}

// 获取根目录文件列表
export async function updateRootDirectoryFileList() {
    // minio 根目录
    currentPath.value = ''
    selectedItem.value = null

    // 清空数组
    pathHistory.value = [];
    await updateCurrentPathFileList();
}

// 进入指定文件夹，并刷新文件列表
export async function updateSpecifyFolderDirectoryFileList(path: string) {
    currentPath.value = path;
    pathHistory.value.push(currentPath.value);
    selectedItem.value = null;

    clearSearch()
    await updateCurrentPathFileList();
}

// 返回上一级
async function navigateUp() {
    clearSearch()
    console.log("执行返回上一级，当前目录为", currentPath.value);
    if (pathHistory.value.length > 0) {
        pathHistory.value.pop();
        if (pathHistory.value.length > 0) {
            currentPath.value = pathHistory.value[pathHistory.value.length - 1];
        } else {
            currentPath.value = ''
        }

    } else {
        // 如果没有历史记录，从当前路径解析上一级目录
        if (currentPath.value) {
            // 处理路径分隔符，兼容不同操作系统
            const pathParts = currentPath.value.split(/[\\/]/).filter(part => part);

            // 移除最后一级路径
            pathParts.pop();
            // 重新构建路径
            currentPath.value = pathParts.length > 0 ? pathParts.join('/') : '';

        }
    }
    console.log("要跳转的目的路径", currentPath.value);
    selectedItem.value = null;
    await updateCurrentPathFileList();
}

// 清空搜索
export const clearSearch = () => {
    searchKeyword.value = '';
};

// --------------------- 预览文件 方法区域 --------------

async function previewFileItem(fileItem: StarFileItem) {

    await handlePreview(fileItem.bucket, fileItem.path, fileItem.name, fileItem.fullPath)

}

// 预览 当前选中的文件
async function previewCurrentFileItem() {
    if (!selectedItem.value || selectedItem.value.folderFlag) return;

    await handlePreview(currentBucketName.value, currentPath.value, selectedItem.value.name, selectedItem.value.path)

}

/**
 *  预览回调
 */
async function handlePreview(bucket: string, currentPath: string, fileName: string, fileAbsPath: string) {

    let fileType = fileAbsPath.substring(fileAbsPath.lastIndexOf(".") + 1);
    let type = getFileType(fileType)
    switch (type) {
        case 'docx':
        case 'xlsx':
        case 'pptx':
        case 'pdf':
            handlePreviewOffice(bucket, currentPath, fileName)
            break;
        case 'text':
        case 'txt':
        case 'sql':
            await handlePreviewText(bucket, currentPath, fileName, fileAbsPath)
            break;
        case 'html':
            await handlePreviewRichText(bucket, currentPath, fileName, fileAbsPath)
            break;
        case 'image':
            await handlePreviewImage(bucket, fileAbsPath)
            break;

        default:
            message("文件格式不支持预览，请直接下载", 'warning')
    }

}

/**
 * 预览office文件
 */
function handlePreviewOffice(bucket: string, path: string, fileName: string) {
    router.push({
        path: '/fileBrowser/editor/office',
        query: {
            fileName: fileName,
            filePath: path + '/',
            bucket: bucket
        }
    });

}

/**
 * 预览纯文本文件
 */
async function handlePreviewText(bucket: string, _currentPath: string, fileName: string, fileAbsPath: any) {
    await router.push({
        path: '/fileBrowser/editor/text',
        query: {
            fileName: fileName,
            filePath: _currentPath,
            fileFullPath: fileAbsPath,
            bucket: bucket
        }
    })
}

/**
 * 预览 RichText 文件
 */
async function handlePreviewRichText(bucket: string, _currentPath: string, fileName: string, fileAbsPath: any) {

    await router.push({
        path: '/fileBrowser/editor/richText',
        query: {
            fileName: fileName,
            filePath: _currentPath,
            fileFullPath: fileAbsPath,
            bucket: bucket
        }
    })

}

/**
 * 预览 图片 文件
 */
async function handlePreviewImage(bucket: string, fileAbsPath: string) {

    let res: any;
    res = await getBucketFileUrl(bucket, fileAbsPath)

    if (res.data.code === 200) {
        await router.push({
            path: '/fileBrowser/editor/image',
            query: {
                imageUrl: res.data.data
            }
        })

    } else {
        message("获取图片失败", 'error')
    }
}


// ------------------- 拖动文件 -----------------------
/**
 * 处理拖放文件到上一级目录
 */
const handleParentFolderDrop = async () => {
    if (!draggedItem.value) return;

    try {
        // 获取上一级目录路径
        let parentPath = '';

        // MinIO存储
        const pathParts = currentPath.value.split('/').filter(Boolean);
        if (pathParts.length > 0) {
            pathParts.pop();
            parentPath = pathParts.join('/');
        }

        let str = `移动文件: ${draggedItem.value.path} 到上一级目录 ${parentPath}/${draggedItem.value.name}`

        let res: any = await moveBucketFile({
            bucketName: currentBucketName.value,
            sourceFilePath: draggedItem.value.path,
            targetFolderPath: parentPath
        })

        if (res.data.code == 200) {
            await updateCurrentPathFileList();
            message(str, 'success');
        } else {
            message('文件移动失败', 'error');
        }

    } catch (error) {
        console.error('移动文件失败:', error);
        message('文件移动失败', 'error');
    } finally {
        draggedItem.value = null;
        dragOverParentFolder.value = false;
    }
};
/**
 * 处理文件拖放，用户移动文件目录
 */
const handleDrop = async (targetFolder: FileItem) => {
    if (!draggedItem.value || !targetFolder.folderFlag) return;

    try {
        // 这里只打印，不实际调用后端接口
        let str = `移动文件: ${draggedItem.value.path} 到 ${targetFolder.path}`;

        let res: any;

        res = await moveBucketFile({
            bucketName: currentBucketName.value,
            sourceFilePath: draggedItem.value.path,
            targetFolderPath: targetFolder.path
        })


        if (res.data.code == 200) {
            // 模拟调用后端接口后的刷新
            await updateCurrentPathFileList();
            message('文件移动成功: ' + str, 'success');
        } else {
            message('文件移动失败', 'error');
        }

    } catch (error) {
        console.error('移动文件失败:', error);
        message('文件移动失败', 'error');
    } finally {
        draggedItem.value = null;
        dragOverItem.value = null;
    }
};


// -------------------- 工具区域 -----------------------

// 添加排序方法
const sortBy = (field: 'name' | 'size' | 'lastModified') => {
    if (sortField.value === field) {
        sortOrder.value = sortOrder.value === 'asc' ? 'desc' : 'asc';
    } else {
        sortField.value = field;
        sortOrder.value = 'asc';
    }

    setFileBrowserSortConfig(sortField.value + '-' + sortOrder.value);
};

// 从LocalStorage 读取排序配置
function getOriginSortConfig() {
    let config: string = getFileBrowserSortConfig()

    sortField.value = config.split('-')[0];
    sortOrder.value = config.split('-')[1];
}


// 获取文件图标
export const getFileIcon = (fileName: string): string => {
    const fileType = getFileType(fileName);
    switch (fileType) {
        case 'pdf':
            return pdfIcon;
        case 'docx':
            return wordIcon;
        case 'xlsx':
            return excelIcon;
        case 'pptx':
            return pptIcon;
        case 'image':
            return imageIcon;
        case 'audio':
            return audioIcon;
        case 'video':
            return videoIcon;
        case 'zip':
            return archiveIcon;
        case 'html' :
            return htmlIcon;
        case 'txt':
            return textIcon;
        case 'text':
            return wenBenIcon;
        case 'sql':
            return sqlIcon;
        case 'exe':
            return chengXuIcon;
        default:
            return fileIcon;
    }
};


// 格式化文件大小
export const formatFileSize = (bytes: number) => {
    if (bytes === 0) return '0 Bytes';
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
};

// 格式化日期
export const formatDate = (item: any) => {
    if (item.lastModified) {
        return item.lastModified.toLocaleString();
    } else {
        return '-'
    }

};

export {
    currentBucketName, // 当前Bucket名，使用用户名
    currentMenu,
    currentPath,   // 文档浏览器当前目录
    pathHistory,   // 文件浏览器历史路径
    canNavigateUp, // 是否能够返回上一级
    loading,       // 文件列表是否在加载中
    searchKeyword,
    updateCurrentPathFileList,
    navigateUp,    //返回上一级，并加载文件列表
    previewCurrentFileItem, // 预览当前选中的文件
    previewFileItem,
    handleDrop,
    handleParentFolderDrop,
    sortBy,
    getOriginSortConfig

}
